package com.bilibili.lzx.api;

import com.alibaba.fastjson2.JSONObject;
import com.bilibili.lzx.api.support.UserSupport;
import com.bilibili.lzx.dao.domain.JsonResponse;
import com.bilibili.lzx.dao.domain.User;
import com.bilibili.lzx.dao.domain.UserInfo;
import com.bilibili.lzx.service.UserService;
import com.bilibili.lzx.service.util.RSAUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;


@RestController
public class UserApi {
    @Autowired
    private UserService userService;

    @Autowired
    private UserSupport userSupport;

    @GetMapping("/rsa-pks")
    public JsonResponse<String> getPublicKey(){
        String publicKeyStr = RSAUtil.getPublicKeyStr();
        return new JsonResponse<>(publicKeyStr);
    }

    @GetMapping("/users")
    public JsonResponse<User> getUser() {
        Long currentUserId = UserSupport.getCurrentUserId();
        User user = userService.getUserInfo(currentUserId);
        return new JsonResponse<>(user);
    }

    @PostMapping("/users")
    public JsonResponse<Integer> addUser(@RequestBody User user) {
        int i = userService.addUser(user);
        return new JsonResponse<>(i);
    }

    @PostMapping("/user-tokens")
    public JsonResponse<String> login(@RequestBody User user){
        System.out.println(user);
        String token = userService.login(user);
        return new JsonResponse<>(token);
    }

    @GetMapping("/user-info-pages")
    public JsonResponse<PageInfo<UserInfo>> pageListUserInfos(@RequestParam(defaultValue = "1") Integer no, @RequestParam(defaultValue = "5") Integer size, String nick){
        Long currentUserId = UserSupport.getCurrentUserId();
        JSONObject params = new JSONObject();
        params.put("no",no);
        params.put("size",size);
        params.put("nick",nick);
        params.put("userId",currentUserId);
        PageInfo<UserInfo> userInfos = userService.pageListUserInfos(params);
        return new JsonResponse<>(userInfos);
    }




    @PostMapping("/videos")
    public JsonResponse<String> uploadVideo(MultipartFile video) throws IOException {
        String originalFilename = video.getOriginalFilename();
        System.out.println(video.getContentType());
        System.out.println(originalFilename);
        //InputStream inputStream = video.getInputStream();
        //FileOutputStream fileOutputStream = new FileOutputStream(originalFilename);
        File diskPath = new File("D:/",originalFilename);
        video.transferTo(diskPath);
        System.out.println(diskPath.getAbsolutePath());

        //new FileInputStream(inputStream);
        //int read = inputStream.read();
        //System.out.println(read);
        return JsonResponse.success();
    }
}
